<template>
  <div class="data-driven">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>数据驱动测试配置</span>
          <el-button type="primary" @click="showCreateDialog = true">
            <el-icon><plus /></el-icon>
            新建配置
          </el-button>
        </div>
      </template>

      <!-- 数据源列表 -->
      <el-table :data="dataSources" border v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="数据源名称" min-width="200" />
        <el-table-column prop="type" label="类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeColor(row.type)">
              {{ getTypeName(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="project_name" label="关联项目" width="150" />
        <el-table-column prop="data_count" label="数据条数" width="120">
          <template #default="{ row }">
            <el-badge :value="row.data_count" :max="999" />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'info'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewDataSource(row)">查看</el-button>
            <el-button size="small" @click="previewData(row)">预览数据</el-button>
            <el-button size="small" type="primary" @click="executeWithData(row)">
              执行测试
            </el-button>
            <el-button size="small" type="danger" @click="deleteDataSource(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadDataSources"
        @current-change="loadDataSources"
        style="margin-top: 20px; justify-content: center;"
      />
    </el-card>

    <!-- 创建/编辑数据源对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingDataSource ? '编辑数据源' : '新建数据源'"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form :model="dataSourceForm" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="数据源名称" prop="name">
          <el-input v-model="dataSourceForm.name" placeholder="请输入数据源名称" />
        </el-form-item>

        <el-form-item label="关联项目" prop="project_id">
          <el-select v-model="dataSourceForm.project_id" placeholder="请选择项目" style="width: 100%">
            <el-option
              v-for="project in projects"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="关联用例" prop="test_case_id">
          <el-select
            v-model="dataSourceForm.test_case_id"
            placeholder="请选择测试用例"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="testCase in testCases"
              :key="testCase.id"
              :label="testCase.name"
              :value="testCase.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="描述">
          <el-input
            v-model="dataSourceForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述"
          />
        </el-form-item>

        <el-divider>数据源配置</el-divider>

        <DataSourceConfig v-model="dataSourceForm.config" />
      </el-form>

      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 数据预览对话框 -->
    <el-dialog v-model="showPreviewDialog" title="数据预览" width="80%">
      <el-alert
        title="数据预览"
        :description="`共 ${previewDataList.length} 条数据`"
        type="info"
        :closable="false"
        style="margin-bottom: 20px;"
      />

      <el-table :data="previewDataList" border max-height="500">
        <el-table-column
          v-for="(value, key) in (previewDataList[0] || {})"
          :key="key"
          :prop="key"
          :label="key"
          min-width="150"
        >
          <template #default="{ row }">
            <el-tag v-if="typeof row[key] === 'boolean'">
              {{ row[key] }}
            </el-tag>
            <span v-else>{{ row[key] }}</span>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <el-button @click="showPreviewDialog = false">关闭</el-button>
        <el-button type="primary" @click="executeWithPreviewData">
          使用此数据执行测试
        </el-button>
      </template>
    </el-dialog>

    <!-- 执行配置对话框 -->
    <el-dialog v-model="showExecuteDialog" title="执行数据驱动测试" width="600px">
      <el-form :model="executeForm" label-width="120px">
        <el-form-item label="数据源">
          <el-input :value="currentDataSource.name" disabled />
        </el-form-item>

        <el-form-item label="测试用例">
          <el-select
            v-model="executeForm.test_case_id"
            placeholder="请选择测试用例"
            style="width: 100%"
          >
            <el-option
              v-for="testCase in testCases"
              :key="testCase.id"
              :label="testCase.name"
              :value="testCase.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="执行环境">
          <el-select v-model="executeForm.environment" placeholder="请选择环境">
            <el-option label="开发环境" value="dev" />
            <el-option label="测试环境" value="test" />
            <el-option label="预发布环境" value="staging" />
            <el-option label="生产环境" value="prod" />
          </el-select>
        </el-form-item>

        <el-form-item label="并发数">
          <el-input-number v-model="executeForm.concurrency" :min="1" :max="10" />
          <span style="margin-left: 10px; color: #909399;">
            建议根据服务器性能设置
          </span>
        </el-form-item>

        <el-form-item label="失败后继续">
          <el-switch v-model="executeForm.continue_on_failure" />
          <span style="margin-left: 10px; color: #909399;">
            开启后，某条数据执行失败不影响其他数据
          </span>
        </el-form-item>

        <el-form-item label="生成报告">
          <el-switch v-model="executeForm.generate_report" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showExecuteDialog = false">取消</el-button>
        <el-button type="primary" @click="handleExecute" :loading="executing">
          开始执行
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getDataSources,
  createDataSource,
  updateDataSource,
  deleteDataSource as deleteDataSourceAPI,
  previewDataSource
} from '@/api/dataSources'
import { getProjects } from '@/api/projects'
import { getTestCases } from '@/api/testCases'
import { dataDrivenExecute } from '@/api/execution'
import DataSourceConfig from '@/components/DataSourceConfig.vue'

const loading = ref(false)
const saving = ref(false)
const executing = ref(false)
const showCreateDialog = ref(false)
const showPreviewDialog = ref(false)
const showExecuteDialog = ref(false)

const dataSources = ref([])
const projects = ref([])
const testCases = ref([])
const previewDataList = ref([])
const editingDataSource = ref(null)
const currentDataSource = ref({})
const formRef = ref(null)

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const dataSourceForm = reactive({
  name: '',
  project_id: null,
  test_case_id: null,
  description: '',
  config: {}
})

const executeForm = reactive({
  test_case_id: null,
  environment: 'test',
  concurrency: 1,
  continue_on_failure: true,
  generate_report: true
})

const rules = {
  name: [{ required: true, message: '请输入数据源名称', trigger: 'blur' }],
  project_id: [{ required: true, message: '请选择项目', trigger: 'change' }],
  test_case_id: [{ required: true, message: '请选择测试用例', trigger: 'change' }]
}

onMounted(() => {
  loadDataSources()
  loadProjects()
  loadTestCases()
})

const loadDataSources = async () => {
  loading.value = true
  try {
    const result = await getDataSources({
      page: pagination.page,
      size: pagination.size
    })

    dataSources.value = result.data || []
    pagination.total = result.total || 0
  } catch (error) {
    ElMessage.error('加载数据源失败')
  } finally {
    loading.value = false
  }
}

const loadProjects = async () => {
  try {
    const result = await getProjects()
    projects.value = result.data || []
  } catch (error) {
    console.error('加载项目失败:', error)
  }
}

const loadTestCases = async () => {
  try {
    const result = await getTestCases()
    testCases.value = result.data || []
  } catch (error) {
    console.error('加载用例失败:', error)
  }
}

const handleSave = async () => {
  try {
    await formRef.value.validate()

    saving.value = true
    
    if (editingDataSource.value) {
      await updateDataSource(editingDataSource.value.id, dataSourceForm)
      ElMessage.success('更新成功')
    } else {
      await createDataSource(dataSourceForm)
      ElMessage.success('创建成功')
    }

    showCreateDialog.value = false
    loadDataSources()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('保存失败')
    }
  } finally {
    saving.value = false
  }
}

const viewDataSource = (dataSource) => {
  editingDataSource.value = dataSource
  Object.assign(dataSourceForm, dataSource)
  showCreateDialog.value = true
}

const previewData = async (dataSource) => {
  try {
    const result = await previewDataSource(dataSource.id, { limit: 10 })
    previewDataList.value = result.data || []
    currentDataSource.value = dataSource
    showPreviewDialog.value = true
  } catch (error) {
    ElMessage.error('预览数据失败')
  }
}

const executeWithData = (dataSource) => {
  currentDataSource.value = dataSource
  executeForm.test_case_id = dataSource.test_case_id
  showExecuteDialog.value = true
}

const executeWithPreviewData = () => {
  showPreviewDialog.value = false
  executeWithData(currentDataSource.value)
}

const handleExecute = async () => {
  if (!executeForm.test_case_id) {
    ElMessage.warning('请选择测试用例')
    return
  }

  executing.value = true
  try {
    const result = await dataDrivenExecute({
      data_source_id: currentDataSource.value.id,
      test_case_id: executeForm.test_case_id,
      environment: executeForm.environment,
      concurrency: executeForm.concurrency,
      continue_on_failure: executeForm.continue_on_failure,
      generate_report: executeForm.generate_report
    })

    if (result.success) {
      ElMessage.success('测试已开始执行，请到执行监控页面查看进度')
      showExecuteDialog.value = false
    }
  } catch (error) {
    ElMessage.error('执行失败：' + error.message)
  } finally {
    executing.value = false
  }
}

const deleteDataSource = async (dataSource) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除数据源"${dataSource.name}"吗？`,
      '提示',
      { type: 'warning' }
    )

    await deleteDataSourceAPI(dataSource.id)
    ElMessage.success('删除成功')
    loadDataSources()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const getTypeName = (type) => {
  const names = {
    excel: 'Excel',
    json: 'JSON',
    csv: 'CSV',
    mysql: 'MySQL'
  }
  return names[type] || type
}

const getTypeColor = (type) => {
  const colors = {
    excel: 'success',
    json: 'primary',
    csv: 'warning',
    mysql: 'danger'
  }
  return colors[type] || ''
}
</script>

<style scoped>
.data-driven {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
